package com.yuting.code.controller;

import com.sun.corba.se.spi.servicecontext.CodeSetServiceContext;
import com.yuting.code.dao.CodeDao;
import com.yuting.code.service.CodeService;
import com.yuting.common.pojo.AuthCode;
import lagou.service.dubbo.api.RpcEmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("code")
@Slf4j
public class CodeController {

    @Autowired
    private CodeService codeService;


    @Reference
    private RpcEmailService rpcEmailService;

    @Autowired
    private CodeDao codeDao;

    @GetMapping("/create/{email}")
    public Boolean createCode(@PathVariable("email") String email, HttpServletResponse response){
        //生成code
        String code = codeService.codeGenerate(6);

        //落库
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        Calendar instance = Calendar.getInstance();
        authCode.setCreateTime(instance.getTime());
        instance.add(Calendar.MINUTE, 10);
        authCode.setExpireTime(instance.getTime());
        codeDao.save(authCode);


        return rpcEmailService.sendCode(email, code);
    }

    @GetMapping("validate/{email}/{code}")
    public Integer codeValidate(@PathVariable("email")String email, @PathVariable("code")String code){
        List<AuthCode> all = codeDao.findAllByEmailEqualsAndCodeEquals(email, code);
        // 若找不到该记录，则返回1
        if(all.isEmpty()){
            log.info("找不到email-{}, code-{}",email, code);
            return 1;
        }

        //过滤掉过期的记录
        List<AuthCode> filtered = all.stream()
                .filter(authCode -> authCode.getExpireTime().after(new Date()))
                .collect(Collectors.toList());

        //此时为空，则是超时了
        if(filtered.isEmpty()){
            log.info("过滤之后没有有效的code了！");
            return 2;
        }else{
            return 0;
        }

    }


}
